package com.mql.ganio.ui.presenter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.mql.ganio.ui.adapter.MyPageAdapter;
import com.mql.ganio.ui.adapter.ViewPagerAdapter;
import com.mql.ganio.ui.base.BaseFragmentActivity;
import com.mql.ganio.ui.base.BaseFragmentPresenter;
import com.mql.ganio.ui.view.ViewBigImageAtView;
import com.mql.ganio.util.UIUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 作者：Administrator on 2017/11/8 18:30
 */
public class ViewBigImagePresenter extends BaseFragmentPresenter<ViewBigImageAtView> {
    ViewPagerAdapter adapter;
    BaseFragmentActivity context;
    boolean isApp;
    int imageId;
    List<String> imgList;
    boolean isLocal;
    int selet;
    int code;
    int page=0;
    public ViewBigImagePresenter(BaseFragmentActivity context) {
        super(context);
    }

    public ViewBigImagePresenter(BaseFragmentActivity context, boolean isLocal, int imageId, boolean isApp, int selet, int code, final List<String> imgList) {
        super(context);
        this.context=context;
        this.isApp=isApp;
        this.imageId=imageId;
        this.imgList=imgList;
        this.isLocal=isLocal;
        this.selet=selet;
        this.code=code;
       // setAdapter();

    }

    public void setAdapter() {
        /**
         * 给viewpager设置适配器
         */
        if (isApp) {
            MyPageAdapter myPageAdapter = new MyPageAdapter(context,imageId);
            getView().getHackyViewPager().setAdapter(myPageAdapter);
            getView().getHackyViewPager().setEnabled(false);
        } else {
            adapter = new ViewPagerAdapter(context,isLocal,imgList);
            getView().getHackyViewPager().setAdapter(adapter);
            getView().getHackyViewPager().setCurrentItem(code);
            page = code;
            getView().getHackyViewPager().setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    // 每当页数发生改变时重新设定一遍当前的页数和总页数
                    getView().getVeryImageViewpagerText().setText((position + 1) + " / " + imgList.size());
                    page = position;
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            getView().getHackyViewPager().setEnabled(false);
            // 设定当前的页数和总页数
            if (selet == 2) {
                getView().getVeryImageViewpagerText().setText((code + 1) + " / " + imgList.size());
            }
        }
    }

    public void saveImg(){
        UIUtils.showToast("开始下载图片");
        if (isApp) {// 本地图片
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), imageId);
            if (bitmap != null) {
                saveImageToGallery(context, bitmap);
                UIUtils.showToast("保存成功");
            }

        } else {// 网络图片
            final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            new Thread(new Runnable() {
                @Override
                public void run() {
                // 子线程获得图片路径
                    final String imagePath = getImagePath(imgList.get(page));
                    // 主线程更新
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (imagePath != null) {
                                Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
                                if (bitmap != null) {
                                    saveImageToGallery(context, bitmap);
                                    UIUtils.showToast("已保存至" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/GAnio相册");
                                }
                            }
                        }
                    });
                }
            }).start();
        }
    }

    /**
     * 保存图片至相册
     */
    public static void saveImageToGallery(Context context,Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "GAnio相册");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsoluteFile())));
    }


    /**
     * Glide 获得图片缓存路径
     */
    private String getImagePath(String imgUrl) {
        String path = null;
        FutureTarget<File> future = Glide.with(context)
                .load(imgUrl)
                .downloadOnly(500, 500);
        try {
            File cacheFile = future.get();
            path = cacheFile.getAbsolutePath();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return path;
    }

}
